package cs2340.klondike.TaskFudger;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.stmt.Where;

import db.DatabaseHelper;
import models.Task;
import models.User;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import models.*;

/** 
 * Once the user has successfully logged in, this class is loaded as the main Activity where all the tasks are displayed
 * @version 1.0 
**/
@SuppressWarnings("unchecked")
public class TasksActivity extends OrmLiteBaseActivity<DatabaseHelper> {
	//================================================================================================================================================
	//Declare instance variables
	//================================================================================================================================================
	private ListView tasksList;
	private Spinner sortBySpinner;
	private Button newTask;
	private ArrayAdapter<String> adapter;
	List<Task> tasks;
	List<Category> categories;
	ArrayList<String> tasksAsStrings;
	Task selectedTask;
	static final int DATE_DIALOG_ID = 0;
	static final int CATEGORY_DIALOG_ID = 1;
	static final int COMPLETION_DIALOG_ID = 2;
	static final int PRIORITY_DIALOG_ID = 3;	
	private int filterDay;
	private int filterMonth;
	private int filterYear;
	private Date filterDate;
	private Category filterCategory;
	private int filterPriority;
	ForeignCollection<Task> tasksArray;
	
    
    
	/**
     *  Called when the activity is first created. 
     *  Creates the layout
     * */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    public void onStart(){
    	super.onStart();
        setContentView(R.layout.tasks);
        sortBySpinner = (Spinner) findViewById(R.id.spinner);
        tasksList = (ListView) findViewById(R.id.tasksList); 
        newTask = (Button) findViewById(R.id.newTask);
         
        
        //============================================================================================================================================
        //sets up the sort by option spinner
        //============================================================================================================================================
        ArrayAdapter<CharSequence> sortAdapter = ArrayAdapter.createFromResource(this, R.array.sortbyoptions, android.R.layout.simple_spinner_item);
        sortAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sortBySpinner.setAdapter(sortAdapter);
 
        sortBySpinner.setOnItemSelectedListener(
        		new OnItemSelectedListener(){
        			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        				String sortOption = parent.getItemAtPosition(pos).toString();
        				if (sortOption.equals("All")){
        					//display all tasks
        					Where<Task, Integer> where = Task.getDefaultDao().queryBuilder().where();
        					try {
    	    		        	where = where.eq("user_id", User.getCurrentUser().getId());
    	    		        	
    	    		        	filterTasks(where);
    	    		        }
    	    		        
    	    		        catch(SQLException e1)
    	    		        {
    	    		        	// TODO Auto-generated catch block
    	    		        	e1.printStackTrace();
    	    		        }
        					
        					Log.d("Sort Option", "All");
        				}
        				if (sortOption.equals("Category")){
        					//pull up category selection menu
        					showDialog(CATEGORY_DIALOG_ID);
        					Log.d("Sort Option", "Category");
        				}
        				if (sortOption.equals("Due Date")){
        					showDialog(DATE_DIALOG_ID);
        					//filter by due date
        					Log.d("Sort Option", "Due Date");
        				}
        				if (sortOption.equals("Completion Status")){
        					showDialog(COMPLETION_DIALOG_ID);
        					//filter by completed
        					Log.d("Sort Option", "Completion Status");
        				}
        				if(sortOption.equals("Priority")){
    						showDialog(PRIORITY_DIALOG_ID);
    						//filter by priority
    						Log.d("Sort Option", "Priority");
    					}
        				sortBySpinner.setSelection(0);
        			}
        			public void onNothingSelected(AdapterView<?> parent) {
        				//do nothing
        			}
        		});

        //============================================================================================================================================
        //sets up the date picker
        //============================================================================================================================================
       
        final Calendar c = Calendar.getInstance();
        filterYear = c.get(Calendar.YEAR);
        filterMonth = c.get(Calendar.MONTH);
        filterDay = c.get(Calendar.DAY_OF_MONTH);
 
        //============================================================================================================================================
        //sets up the task list
        //============================================================================================================================================

        setTaskList();
        tasksList.setOnItemClickListener(
        		new OnItemClickListener(){
        			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        				// TODO Auto-generated method stub
        				tasksList.setSelection(position);
        				selectedTask = tasks.get(position);
						Log.i("DBSTUFF", tasksAsStrings.get(position));
		 				try {
			 				Intent intent = new Intent(view.getContext(), NewTaskActivity.class); 
							intent.putExtra("TASK_ID", selectedTask.extractId());
					        startActivity(intent);
					        setTaskList();
						} 
		 				catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		         	} 
        		}
        );      
        
        //============================================================================================================================================
        //sets up the new task button
        //============================================================================================================================================
         
        newTask.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), NewTaskActivity.class); 
				startActivity(intent);
		        setTaskList();
			}
		}
        		
        );
        
   
    }
    private void setTaskList() {
        try {
			User.getCurrentUser().refresh();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	tasksArray = User.getCurrentUser().getTasks();
        
       	tasksAsStrings = new ArrayList<String>();
       	tasks = new ArrayList<Task>();
        for (Task t : tasksArray) {
        	tasks.add(t);
        	tasksAsStrings.add(t.toString());
        }
        
        Log.i("CONVERTINGTOSTRING", tasksAsStrings.toString());
        
        adapter = new ArrayAdapter<String>(TasksActivity.this, android.R.layout.simple_list_item_1, tasksAsStrings);
        tasksList.setAdapter(adapter);
    }
    
	private void filterTasks(Where<Task, Integer> query) throws SQLException {
		tasks = Task.getDefaultDao().query(query.prepare());
		
		
		tasksAsStrings = new ArrayList<String>();
        for (Task t : tasks) {
        	tasksAsStrings.add(t.toString());
        }
        
        Log.i("CONVERTINGTOSTRING", tasksAsStrings.toString());
		
        //addAll(Collection) not supported in API 10
		adapter.clear();
        for (String str:tasksAsStrings){
        	adapter.add(str);
        }
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
    {
    	
		public void onDateSet(DatePicker view, int year, int month, int day)
    	{
    		filterYear = year;
            filterMonth = month;
            filterDay = day;
            filterDate = new Date(year, month, day);
            
            Where<Task, Integer> where = Task.getDefaultDao().queryBuilder().where();
            
            try {
				where = where.and(
						where.ge("dueDate", filterDate),
						where.eq("user_id", User.getCurrentUser().getId())
				);
				
				filterTasks(where);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        }
    };
    protected Dialog onCreateDialog(int id) 
	{
	    switch (id) 
	    {
	    	case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, filterYear, filterMonth, filterDay);
	    	case CATEGORY_DIALOG_ID: {
	    		ForeignCollection<Category> categoriesList = User.getCurrentUser().getCategories();
	    		categories = new ArrayList<Category>();
	    		
	    		final CharSequence[] items = new CharSequence[categoriesList.size()];
	    		
	    		int i = 0;
	    		for (Category c : categoriesList) {
	    			items[i] = c.toString();
	    			categories.add(c);
	    			i++;
	    		}
	    		
	    		//final CharSequence[] items = {"Sample Category 1", "Sample Category 2", "Sample Category 3"};

	    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    		builder.setTitle("Pick a Category");
	    		builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	    		    public void onClick(DialogInterface dialog, int item) {
	    		        //get Filter category
		    		    	
	    		    	filterCategory = categories.get(item);	//holds the category selected by the user
	    		    	
	    		    	Where<Task, Integer> where = Task.getDefaultDao().queryBuilder().where();
	    		    	try {
	    						where = where.and(
	    								where.eq("category_id", filterCategory.getId()),	    							
	    								where.eq("user_id", User.getCurrentUser().getId())
	    						);
	    					filterTasks(where);
	    				} catch (SQLException e2) {
	    					// TODO Auto-generated catch block
	    					e2.printStackTrace();
	    				}
	    		    	
	    		    	dialog.dismiss();
	    		    }
	    		});
	    		AlertDialog alert = builder.create();
	    		return alert;
	    	}
	    	case COMPLETION_DIALOG_ID: {
	    		final CharSequence[] items = {"Not Completed", "Completed"};

	    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    		builder.setTitle("Filter by Completion");
	    		builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	    		    public void onClick(DialogInterface dialog, int item) {
	    		        Where<Task, Integer> where = Task.getDefaultDao().queryBuilder().where();
	    		        //Added the completed filter query.
	    		        try {
	    		        	where = where.and(
	    		        			where.eq("completed", item == 1),
	    		        			where.eq("user_id", User.getCurrentUser().getId())
    						);
	    		        	
	    		        	filterTasks(where);
	    		        }
	    		        
	    		        catch(SQLException e1)
	    		        {
	    		        	// TODO Auto-generated catch block
	    		        	e1.printStackTrace();
	    		        }
	    		    
	    		    	dialog.dismiss();
	    		    }
	    		});
	    		AlertDialog alert = builder.create();
	    		return alert;
	    	}
	    	
	    	case PRIORITY_DIALOG_ID: {
	    		
	    		String[] items = Priority.priorityStrings;
	    		
	    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    		builder.setTitle("Filter by Priority");
	    		builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	    		
	    			public void onClick(DialogInterface dialog, int item) {
	    		        		    		    	
	    		    	filterPriority = item + 1;	
	    		    	
	    		    	Where<Task, Integer> where = Task.getDefaultDao().queryBuilder().where();
	    		    	try {
	    						where = where.and(
	    								where.eq("priority", filterPriority),	    							
	    								where.eq("user_id", User.getCurrentUser().getId())
	    						);
	    						
	    						filterTasks(where);
	    				} 
	    				catch (SQLException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	    		    	
	    		    	dialog.dismiss();
	    		    }
	    		});
	    		AlertDialog alert = builder.create();
	    		return alert;	    	
	    	}
	    }
	    
	    return null;
	}

}